package com.ch14.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName ApplicationContextHolder
 * @Description 使用Aware接口(感知型接口),这样spring容器就会知道当前的这个类需要注入一个容器对象
 * @Author Kx
 * @Date 2025/5/8 11:02
 * @Version 1.0
 */
// 把当前Bean交给容器管理
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    // 容器对象
    private static ApplicationContext applicationContext;

    /**
     * @author: kx
     * @date: 2025/5/8 11:09
     * @param applicationContext : 容器对象
     * @description: 初始化容器对象
    */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * @author: kx
     * @date: 2025/5/8 11:10
     * @return org.springframework.context.ApplicationContext
     * @description: 获取容器对象
    */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * @author: kx
     * @date: 2025/5/8 11:11
     * @param clazz : 需要获取的bean的class对象
     * @return T
     * @description: 根据class对象获取bean对象
    */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * @author: kx
     * @date: 2025/5/8 11:12
     * @param id : bean对象的唯一标识id
     * @param clazz : 需要获取的bean的class对象
     * @return T
     * @description: 根据id和class对象获取bean对象
    */
    public static <T> T getBean(String id, Class<T> clazz) {
        return applicationContext.getBean(id, clazz);
    }
}
